# 从MySQL中获取ip
# coding=utf-8
import time, sched
import mysql.connector
import Const


def getIp():
	conn = mysql.connector.connect(user=Const.mysql_host, password=Const.mysql_pass, database=Const.mysql_dbname)
	cursor = conn.cursor()


	cursor.execute("SELECT usedNum FROM ipList WHERE id=1;")
	values = cursor.fetchall()
	# 将用到usedNum <= minMark 的数据
	minMark = str(values[0][0])
	# print(values[0][0])  #id=1 的 usedNum 值
	cursor.execute("SELECT * FROM ipList WHERE usedNum<"+(minMark)+" AND id >1;")
	values = cursor.fetchall()
	# print("len:",len(values))
	if len(values)<=0: # 数据全都使用过“一遍”了      
	    newMark = str(int(minMark) + 1)
	    cursor.execute('UPDATE ipList SET usedNum='+newMark+' WHERE id=1')    
	    cursor.execute("SELECT * FROM ipList WHERE usedNum<="+newMark+" AND id >1;")
	    values = cursor.fetchall() 
	    currId = str(values[0][0])
	    currIp = str(values[0][1])

	else: # 还有数据未使用过“一遍”
	    # values = cursor.fetchall()
	    currId = str(values[0][0])
	    currIp = str(values[0][1])

	# print("currId,currIp",currId,currIp)
	# 获取选中数据旧的 usedNum
	cursor.execute("SELECT usedNum FROM ipList WHERE id="+currId+";")
	currValues = cursor.fetchall()
	newUseNum = str(int(str(currValues[0][0]))+1)
	# print("newUseNum",newUseNum,type(newUseNum))
	cursor.execute('UPDATE ipList SET usedNum='+ newUseNum +' WHERE id='+currId+'')
	lastTime = str(time.strftime("%y-%m-%d %H:%M:%S"))
	print("lastTime",lastTime,type(lastTime))
	cursor.execute('UPDATE ipList SET lastUsedTime=%s WHERE id=%s;',(lastTime,currId))

	conn.commit()
	cursor.close()    
	conn.close()
	return currIp